package com.dmbjz.diners.service;

import cn.hutool.core.util.RandomUtil;
import com.dmbjz.common.constant.RedisKeyConstant;
import com.dmbjz.common.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/*验证码Service*/
@Service
public class SendVerifyCodeService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /*发送验证码*/
    public String send(String phone){

        AssertUtil.isNotEmpty(phone,"手机号不能为空!");
        String key = RedisKeyConstant.verify_code.getKey() + phone;
        if(checkCode(key,phone)){
            String code = RandomUtil.randomNumbers(6);//生成6位数验证码
            redisTemplate.opsForValue().set(key,code,60, TimeUnit.SECONDS);
            return code;
        }
        return redisTemplate.opsForValue().get(key);//获取验证码

    }

    /*根据手机号查询验证码是否过期*/
    public boolean checkCode(String key,String phone){

        Long expire = redisTemplate.getExpire(key);//获取Key的过期时间
        return expire.equals(-2L)? true:false;

    }

    /*根据手机号获取验证码*/
    public String getCodeByPhone(String phone){
        String key = RedisKeyConstant.verify_code.getKey() + phone;
        return redisTemplate.opsForValue().get(key);//获取验证码
    }


}
